package son.hut.vn;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDataOpenHelper {
	public static final String DB_NAME="student.db";
	public static final String TB_NAME="student";
	public static final int DB_VERSION=1;
	
	private Context mContext;
	private SQLiteDatabase sqLiteDatabase;
	
	public MyDataOpenHelper(Context context){
		this.mContext = context;
		myOpenHelper openHelper = new myOpenHelper(mContext);
		sqLiteDatabase = openHelper.getWritableDatabase();
	}
	
	//tai day se xay dung cac phuong thuc de thuc hien viec thao tac voi database
	//select, insert, update, delete...
	public void insertStudent(String name, int phone){
		ContentValues contentValues = new ContentValues();
		contentValues.put("Name", name);
		contentValues.put("Phone", phone);
		sqLiteDatabase.insertOrThrow(TB_NAME, null, contentValues);
	}
	
	public void deleteStudent(int id){
		sqLiteDatabase.delete(TB_NAME, "_id= "+ id, null);
	}
	
	public void updateStudent(int id, String name, int phone){
		ContentValues contentValues = new ContentValues();
		contentValues.put("Name", name);
		contentValues.put("Phone", phone);
		sqLiteDatabase.update(TB_NAME, contentValues, "_id= "+id, null);
	}
	
	public Cursor selectStudents(){
		return sqLiteDatabase.query(TB_NAME, null, null, null, null, null, null);
	}
	
	public class myOpenHelper extends SQLiteOpenHelper{

		public myOpenHelper(Context context) {
			super(context, DB_NAME, null, DB_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			//tai day se thuc hien tao ra cac bang
			db.execSQL("create table if not exists student(_id integer primary key autoincrement, Name text, Phone integer)");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			//neu co su thay doi thi xoa cac bang va tao lai
			db.execSQL("drop table if exists student");
			onCreate(db);
		}
		
	}
}
